package test2;


import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
 * @author liule
 * @date 2023/8/7 14:37
 * @Desc : 发送application/x-www-form-urlencoded类型的post请求
 */
public class HttpClientTest4_post {
    public static void main(String[] args) throws Exception {
        //可关闭的httpclient客户端，相当于你打开的一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String urlstr = "http://localhost:8899/httpclient-demo/test2";

        // 创建HttpPost
        HttpPost httpPost = new HttpPost(urlstr);
        //设置请求头 HttpPost请求头默认Content-type为application/x-www-form-urlencoded
        httpPost.addHeader( "Content-Type" ,  "application/x-www-form-urlencoded; charset=utf-8");

        //给post对象设置参数
        /*
        NameValuePair:<input id="user-name-label" type="text" name="userWame " >
        的name(userName)和Kinput标签里面输入的值就构成了一个NameValuePair对象
         */
        ArrayList<NameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("userName", "乐之者java"));
        list.add(new BasicNameValuePair("password", "tanguanggad"));
        // 将参数集合设置到formEntity
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, Consts.UTF_8);
        httpPost.setEntity(formEntity);

        // 可关闭的响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpPost);
            // 代表本次请求的成功失败的状态
            StatusLine statusLine = response.getStatusLine();
            if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
                HttpEntity entity = response.getEntity();
                String toStringSesult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringSesult);
                EntityUtils.consume(entity); // 确保流关闭
            } else {
                System.out.println("响应失败，响应码：" + statusLine.getStatusCode());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }

    }
}
